// pages/goods/goods.js
const app = new getApp();
import Dialog from '@vant/weapp/dialog/dialog';
import Toast from '@vant/weapp/toast/toast';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    stripe:false,//是否为全面屏
    height: "0px", //页面高度
    popup: false, //隐藏购买弹框
    norm: null, //子商品信息
    normT: true, //真为未选中子商品
    max: 100, //购买数量最大值
    price: {}, //母商品信息
    number: 1, //设置数量
    normList: {}, //子商品信息集合
    userInfo:null,//用户信息
    stock: 0,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.goods();
    this.setData({
      userInfo:app.globalData.userInfo,
    })
    let screenHeight = wx.getSystemInfoSync().screenHeight
    let bottom = wx.getSystemInfoSync().safeArea.bottom
    if(screenHeight!==bottom){
      this.setData({
        height:this.data.height-30,
        stripe:true,
      })
    }
  },
//初始化商品信息
  goods(){
    var price=app.globalData.price;
    var that = this;
    var stock = 0;
    //读取子商品
    wx.request({
      url: app.globalData.url + 'getNorm?product_id=' + price.id,
      method: "POST",
      header: {
        "content-type": "application/x-www-form-urlencoded"
      },
      success(res) {
        res.data.norm.forEach(element => {
          stock += element.stock;
        });
        that.setData({
          stock: stock,
          normList: res.data.norm,
        })
      },
      fail(res) {
        that.setData({
          stock: '',
          normList: null,
        })
        wx.showToast({
          title: '服务器错误！',
          icon: 'error',
          duration: 2000
        })
      }
    })
    this.setData({
      normT: true,
      norm: null,
      normInde: -1,
      price: price,
      number: 1,
    })
  },
    //添加购物车
    addCart() {
      if (this.data.norm == null || this.data.norm == '') {
        Toast({
          message: '请选择分类',
          position: 'bottom'
        });
        return;
      }
      if (app.globalData.userInfo == null) {
        wx.redirectTo({
          url: '../login/login?' + "norm=1&number=" + this.data.number + "&normId=" + this.data.norm.id + "&product_id=" + this.data.norm.product_id,
        })
        wx.hideHomeButton();
        return;
      }
      var that=this;
      wx.request({
        url: app.globalData.url + 'addCart',
        data:{
          user_id:that.data.userInfo.id,
          product_num:that.data.number,
          product_id:that.data.norm.product_id,
          norm_id:that.data.norm.id,
          openId:that.data.userInfo.openId,
        },
        method: "POST",
        header: {
          "content-type": "application/x-www-form-urlencoded"
        },
        success(res) {
          if(res.data.state==1){//添加成功
            Dialog.confirm({
              title: '加入购物车',
              message: '加入购物车成功！是否前往购物车',
            }).then(() => {
                that.onClose();
                setTimeout(function () {
                  let pages = getCurrentPages();
                  let prevPage = pages[pages.length - 2];
                  prevPage.cart();
                  prevPage.setData({
                    class:'class',
                    active:1,
                  })
                  wx.navigateBack({
                    delta: 1
                  })
                  // wx.redirectTo({
                  //   url: '../index/index?cart=1',
                  // })
                  
                },100)
              }).catch(() => {
                // on cancel
              });
          }else if(res.data.state==0){//添加失败
            Dialog.alert({
              title: '加入购物车',
              message: '加入购物车失败！请检查页面是否正确',
            }).then(() => {
              })
          }
        },
        fail(){
          wx.showToast({
            title: '服务器错误！',
            icon: 'error',
            duration: 2000
          })
        }
      })
    },
    //立即购买
    buyNow() {
      if (this.data.norm == null || this.data.norm == '') {
        Toast({
          message: '请选择分类',
          position: 'bottom'
        });
        return;
      }
      if (app.globalData.userInfo == null) {
        wx.redirectTo({
          url: '../login/login?norm=2&' + "number=" + this.data.number + "&normId=" + this.data.norm.id + "&product_id=" + this.data.norm.product_id,
        })
        wx.hideHomeButton();
        return;
      }
      var nordId=[this.data.norm.id.toString()];
      var number=[this.data.number];
      wx.navigateTo({
        url: '../buy/buy?' + "number=" + number + "&normId=" + nordId + "&product_id=" + this.data.norm.product_id,
      })
    },
    //设置数量
    number(event) {
      this.setData({
        number: event.detail, //设置数量
      })
    },
    //隐藏购买弹框
    onClose(e) {
      this.setData({
        popup: false,
      })
    },
    //显示购买弹框
    close(e) {
      this.setData({
        popup: true,
      })
    },
      //选择的分类（子商品）
  norm(e) {
    var norm = e.target.dataset.src;
    var id = norm.id;
    this.setData({
      max: 100
    })
    if (norm.stock < 100) {
      if (this.data.number >= norm.stock) {
        this.setData({
          number: norm.stock,
        })
      }
      this.setData({
        max: norm.stock,
      })
    }
    if (this.data.normInde != id) {
      this.setData({
        normT: false,
        norm: norm,
        normInde: id,
      })
    } else {
      this.setData({
        normT: true,
        norm: null,
        normInde: -1,
      })
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})